const sqlite3 = require('../app/backend/node_modules/sqlite3').verbose();
const db = new sqlite3.Database('../app/backend/data/pph.sqlite');

console.log('🔧 清除服务器上A0101150004错误的整机节拍值...');
console.log('=====================================');

// 1. 检查当前错误状态
console.log('📊 检查当前错误状态:');
db.all(`SELECT record_date, line_name, is_whole_machine, 
               target_takt_time, target_motor_takt_time,
               CASE WHEN is_whole_machine = 1 THEN target_takt_time 
                    ELSE target_motor_takt_time END as should_display_takt
        FROM pph_records 
        WHERE material_code = 'A0101150004' 
        AND line_name IN ('3', '5', '9', '10')
        AND is_whole_machine = 0
        AND target_takt_time IS NOT NULL
        ORDER BY record_date DESC, line_name LIMIT 10`, (err, rows) => {
  if (err) {
    console.error('❌ 查询失败:', err);
    db.close();
    return;
  }
  
  console.log(`📋 发现 ${rows.length} 条错误记录（电机生产却有整机节拍）:`);
  if (rows.length > 0) {
    console.table(rows);
  }
  
  if (rows.length === 0) {
    console.log('✅ 没有发现错误的节拍分配，检查所有记录...');
    
    // 检查所有A0101150004记录的节拍分配情况
    db.all(`SELECT record_date, line_name, is_whole_machine, 
                   target_takt_time, target_motor_takt_time,
                   CASE WHEN is_whole_machine = 1 THEN target_takt_time 
                        ELSE target_motor_takt_time END as should_display_takt
            FROM pph_records 
            WHERE material_code = 'A0101150004' 
            AND line_name IN ('3', '5', '9', '10')
            ORDER BY record_date DESC, line_name LIMIT 10`, (err2, allRows) => {
      if (err2) {
        console.error('❌ 查询所有记录失败:', err2);
      } else {
        console.log('\n📊 A0101150004最新10条记录的节拍分配:');
        console.table(allRows);
        
        // 分析节拍分配情况
        const motorRecords = allRows.filter(r => r.is_whole_machine === 0);
        const wholeRecords = allRows.filter(r => r.is_whole_machine === 1);
        const errorRecords = motorRecords.filter(r => r.target_takt_time !== null);
        
        console.log('\n📈 节拍分配分析:');
        console.log(`- 电机生产记录: ${motorRecords.length} 条`);
        console.log(`- 整机生产记录: ${wholeRecords.length} 条`);
        console.log(`- 错误的电机记录（有整机节拍）: ${errorRecords.length} 条`);
        
        if (errorRecords.length > 0) {
          console.log('\n❌ 发现错误记录，需要修复');
          performFix();
        } else {
          console.log('\n✅ 节拍分配正确');
        }
      }
      db.close();
    });
    return;
  }
  
  // 如果发现错误记录，执行修复
  performFix();
});

function performFix() {
  console.log('\n🔧 开始修复：清除电机生产记录的错误整机节拍值...');
  
  db.run(`UPDATE pph_records 
          SET target_takt_time = NULL
          WHERE material_code = 'A0101150004' 
          AND line_name IN ('3', '5', '9', '10')
          AND is_whole_machine = 0
          AND target_takt_time IS NOT NULL`, function(err) {
    if (err) {
      console.error('❌ 修复失败:', err);
      db.close();
      return;
    }
    
    console.log(`✅ 成功清除 ${this.changes} 条记录的错误整机节拍值`);
    
    // 验证修复结果
    console.log('\n🔍 验证修复结果:');
    db.all(`SELECT record_date, line_name, is_whole_machine, 
                   target_takt_time, target_motor_takt_time,
                   CASE WHEN is_whole_machine = 1 THEN target_takt_time 
                        ELSE target_motor_takt_time END as should_display_takt
            FROM pph_records 
            WHERE material_code = 'A0101150004' 
            AND line_name IN ('3', '5', '9', '10')
            ORDER BY record_date DESC, line_name LIMIT 10`, (err2, results) => {
      if (err2) {
        console.error('❌ 验证失败:', err2);
      } else {
        console.log('📊 修复后的结果:');
        console.table(results);
        
        // 最终统计
        const motorRecords = results.filter(r => r.is_whole_machine === 0);
        const errorRecords = motorRecords.filter(r => r.target_takt_time !== null);
        
        console.log('\n📈 修复统计:');
        if (errorRecords.length === 0) {
          console.log('✅ 所有电机生产记录的整机节拍已正确清除');
          console.log('✅ 节拍字段分配现在完全正确');
        } else {
          console.log(`❌ 仍有 ${errorRecords.length} 条电机记录存在错误的整机节拍`);
        }
      }
      db.close();
    });
  });
}
